<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./todos-Case.css" />
  </head>
  <body>
    <div id="root"></div>
    <script src="https://cdn.bootcdn.net/ajax/libs/react/17.0.1/umd/react.development.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.1/umd/react-dom.development.min.js"></script>
    <script src="https://cdn.bootcss.com/EventEmitter/5.2.4/EventEmitter.min.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <!-- nanoid uuid lib唯一值 -->
    <script type="text/babel">
      const { Component, forceUpdate } = React;
      const emitter = new EventEmitter();
      class Todos extends Component {
        state = {
          todos: [
            { id: "1", schedule: "吃饭", done: false },
            { id: "2", schedule: "睡觉", done: false },
            { id: "3", schedule: "打豆豆", done: false },
          ],
        };
        componentDidMount() {
          emitter.on("input", this.enterPress);
          emitter.on("clearAll", () => {
            const { todos } = this.state;
            // const todosArr = todos.filter((item, index) => {
            //   return item.done === false;
            // });
            this.setState({
              todos: todos.filter((item, index) => !item.done),
            });
          });
          emitter.on("itemChecked", (id, flag) => {
            const { todos } = this.state;
            todos.map((item, index) => {
              if (flag) {
                item.id === id ? (item.done = true) : "";
              } else {
                item.id === id ? (item.done = false) : "";
              }
              this.forceUpdate();
            });
            this.checkedNum();
          });
          emitter.on("handleDelete", (id) => {
            if (window.confirm("确定删除吗?")) {
              const { todos } = this.state;
              const newTodos = todos.filter((item) => {
                return item.id !== id;
              });
              this.setState({
                todos: newTodos,
              });
            }
          });
          emitter.on("handleCheckAll", (isTargetChecked) => {
            const { todos } = this.state;
            const newTodoItems = todos.map((item) => {
              return { ...item, done: isTargetChecked };
            });
            console.log(newTodoItems);
            this.setState({
              todos: newTodoItems,
            });
          });
        }
        enterPress = (keyword) => {
          const { todos } = this.state;
          this.setState({
            todos: [
              ...todos,
              { id: Math.random(), schedule: keyword, done: false },
            ],
          });
          emitter.emit("isReceived");
        };
        checkedNum = () => {
          const { todos } = this.state;
          let num = 0;
          todos.forEach((item, index) => {
            item.done ? num++ : num;
          });
          return num;
        };
        render() {
          return (
            <div className="todo-wrap">
              <Header />
              <List todos={this.state.todos} />
              <Footer
                todos={this.state.todos}
                checkedNum={this.checkedNum()}
                totalCount={this.state.todos.length}
              />
            </div>
          );
        }
      }
      function Header() {
        function keyPress(e) {
          e.keyCode === 13 ? emitter.emit("input", e.target.value) : "";
          emitter.on("isReceived", () => (e.target.value = ""));
        }
        return (
          <div className="todo-header">
            <input
              type="text"
              onKeyDown={keyPress}
              placeholder="请输入你的任务名称，按回车键确认"
            />
          </div>
        );
      }
      function List({ todos }) {
        return (
          <ul className="todo-main">
            {todos.map((todoItem, index) => {
              // return <ListItem key={item.id} {...todoItem} />;
              // return <ListItem key={item.id} id={todoItem.id} schedule={todoItem.schedule} />;
              return <ListItem key={todoItem.id} item={todoItem} />;
            })}
          </ul>
        );
      }
      function ListItem({ item }) {
        const arr = [];
        function checkCheck(e, item) {
          e.target.checked
            ? emitter.emit("itemChecked", item.id, true)
            : emitter.emit("itemChecked", item.id, false);
        }
        function handleDelete() {
          emitter.emit("handleDelete", item.id);
        }
        return (
          <li className="todo-list-item">
            <label>
              <input
                type="checkbox"
                // defaultChecked={item.done}
                checked={item.done}
                onChange={(e) => checkCheck(e, item)}
              />
              <span>{item.schedule}</span>
            </label>
            <button
              onClick={handleDelete}
              className="btn btn-danger"
              style={{ display: "block" }}
            >
              删除
            </button>
          </li>
        );
      }
      function Footer({ todos, checkedNum, totalCount }) {
        function clearAll() {
          emitter.emit("clearAll");
        }
        // 另一种方法计算选中
        function checkedCount() {
          return todos.reduce(
            (previousValue, currentValue) =>
              previousValue + (currentValue.done ? 1 : 0),
            0
          );
        }
        function handleCheckAll({ target }) {
          emitter.emit("handleCheckAll", target.checked);
        }
        return (
          <div className="todo-footer">
            <label>
              <input
                type="checkbox"
                onChange={handleCheckAll}
                checked={
                  checkedNum === totalCount && totalCount !== 0 ? true : false
                }
              />
            </label>
            <span>
              <span>
                已完成{checkedNum}:{checkedCount()}
              </span>
              / 全部{totalCount}:{todos.length}
            </span>
            <button className="btn btn-danger" onClick={clearAll}>
              清除已完成任务
            </button>
          </div>
        );
      }

      ReactDOM.render(
        <div className="todo-container">
          <Todos />
        </div>,
        document.getElementById("root")
      );
    </script>
  </body>
</html>
